﻿define([
    'dojo/_base/declare',
    'esri/geometry/Point',
    'geomap/plugins/layers/DivsLayer',
    'geomap/plugins/Div',
], function (declare, Point, BaseDivsLayer, Div) {
    var OpenLayer = declare([BaseDivsLayer], {
        setData: function (mapView, layer) {
            var me = this;
            var mapUtils = mapView.mapUtils;
            var options = layer.layer || {};
            me.options = options;
            var data = $.extend(true, [], options.data);
            var lngLatArray = mapUtils.toLngLatArray(mapView, data, options);
            var symbolFieldName = options.symbolFieldName || mapView.getSymbolFieldName();

            me.convertSr(mapView, lngLatArray, callback);

            function callback(lngLatArray, sr) {
                lngLatArray.map(function (lngLat, index) {
                    var point = mapUtils.createPoint(mapView, lngLat, { sr: sr });
                    var symbol = lngLat[symbolFieldName] || options.symbol || {};
                    var div = new Div(point);
                    div._layer = me;
                    var _element = div.getElement();
                    var _elementJQ = mapView.jQuery(_element);
                    if (symbol.width) {
                        _elementJQ.width(symbol.width);
                    }
                    if (symbol.height) {
                        _elementJQ.height(symbol.height);
                    }
                    var openInterface = mapUtils.ComjsUtils.openInElement(
                        _element,
                        Object.assign(
                            {
                                onLoaded: function () {
                                    me.add(div);
                                },
                            },
                            symbol
                        )
                    );
                    div.attributes = lngLat;

                    if (index == lngLatArray.length - 1) {
                        if (typeof options.callback == 'function') {
                            options.callback(layer);
                        }
                    }
                });
            }
        },
        getGraphicLocation: function (mapView, esriEvent) {
            var geometry = esriEvent.graphic.geometry;
            var lngFieldName = mapView.getLngFieldName();
            var latFieldName = mapView.getLatFieldName();
            var location = {};
            location[lngFieldName] = geometry.x;
            location[latFieldName] = geometry.y;
            location.sr = this.mapSr;
            return location;
        },
    });
    return OpenLayer;
});
